import { defHttp } from '@/utils/http/axios';
import { isNil } from './util';
import { getStoreCode, getToken, getUserName } from '@/utils/auth';
import { getAppEnvConfig } from '@/utils/env';

export const { VITE_GLOB_API_URL: API_URL } = getAppEnvConfig();
export const siteCode = 'Shop';
export const userFromType = '0';

export const GET = (url, params, options, config) =>
  defHttp.get(
    {
      ...(config ?? {}),
      url: url,
      params: appendArg(params),
      headers: appendHeader(),
    },
    options,
  );
export const POST = (url, data, options, config) =>
  defHttp.post(
    {
      ...(config ?? {}),
      url,
      data: appendArg(data),
      headers: appendHeader(),
    },
    options,
  );

export const PUT = (url, data, options, config) =>
  defHttp.put(
    {
      ...(config ?? {}),
      url,
      data: appendArg(data),
      headers: appendHeader(),
    },
    options,
  );
export const DELETE = (url, data, options, config) =>
  defHttp.delete(
    {
      ...(config ?? {}),
      url,
      data: appendArg(data),
      headers: appendHeader(),
    },
    options,
  );

export function PAGE(url, options) {
  return POST_API(url, options);
}

export function POST_API(url, options) {
  return async (data) => {
    return await defHttp.post(
      {
        url,
        data: appendArg(data),
        headers: appendHeader(),
      },
      options,
    );
  };
}

export function URL(path, data, clean) {
  data ||= {};

  if (clean !== true) {
    data = appendArg(appendHeader(data));
  }

  let url = API_URL + path;
  for (const n of Object.getOwnPropertyNames(data)) {
    if (!url.endsWith('?') && !url.endsWith('&')) {
      url += url.indexOf('?') > -1 ? '&' : '?';
    }

    const value = data[n];
    url += `${n}=${encodeURIComponent(isNil(value) ? '' : value)}`;
  }

  return url;
}

export function appendHeader(content) {
  return commonArg(content);
}

export function appendArg(content) {
  content = commonArg(content);

  content.siteCode ||= siteCode;
  content.storeCode ||= getStoreCode();

  return content;
}

export function commonArg(content) {
  content ||= {};

  content.token ||= getToken() || '';
  content.userName ||= getUserName() || '';
  content.userFromType ||= userFromType;

  return content;
}
